package com.papercutting.platform.controller;

import com.papercutting.platform.common.Result;
import com.papercutting.platform.dto.query.TutorialQuery;
import com.papercutting.platform.dto.response.PageResult;
import com.papercutting.platform.dto.response.TutorialResponse;
import com.papercutting.platform.service.TutorialService;
import com.papercutting.platform.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 教程控制器 - 重构为符合三层架构规范
 */
@Slf4j
@RestController
@RequestMapping("/api/tutorial")
@RequiredArgsConstructor
@Validated
public class TutorialController {
    
    private final TutorialService tutorialService;
    
    /**
     * 获取教程列表
     */
    @GetMapping("/list")
    public Result<PageResult<TutorialResponse>> getTutorialList(TutorialQuery query) {
        log.info("分页查询教程列表: {}", query);
        
        PageResult<TutorialResponse> result = tutorialService.getTutorialPage(query);
        
        return Result.success(result);
    }
    
    /**
     * 获取教程详情
     */
    @GetMapping("/{id}")
    public Result<Map<String, Object>> getTutorialDetail(@PathVariable Long id) {
        log.info("获取教程详情: {}", id);
        
        Map<String, Object> tutorial = tutorialService.getTutorialById(id);
        
        return Result.success(tutorial);
    }
    
    /**
     * 获取推荐教程
     */
    @GetMapping("/recommend")
    public Result<List<TutorialResponse>> getRecommendList(@RequestParam(defaultValue = "5") Integer limit) {
        log.info("获取推荐教程列表: {}", limit);
        
        List<TutorialResponse> recommendList = tutorialService.getRecommendedTutorials(limit);
        
        return Result.success(recommendList);
    }
    
    /**
     * 获取免费教程
     */
    @GetMapping("/free")
    public Result<List<TutorialResponse>> getFreeList(@RequestParam(defaultValue = "10") Integer limit) {
        log.info("获取免费教程列表: {}", limit);
        
        List<TutorialResponse> freeList = tutorialService.getFreeTutorials(limit);
        
        return Result.success(freeList);
    }
    
    /**
     * 搜索教程
     */
    @GetMapping("/search")
    public Result<PageResult<TutorialResponse>> searchTutorial(
            @RequestParam String keyword,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {
        log.info("搜索教程内容: keyword={}, page={}, size={}", keyword, page, size);
        
        TutorialQuery query = new TutorialQuery();
        query.setKeyword(keyword);
        query.setPage(page);
        query.setSize(size);
        
        PageResult<TutorialResponse> result = tutorialService.searchTutorial(keyword, query);
        
        return Result.success(result);
    }
    
    /**
     * 获取分类统计
     */
    @GetMapping("/category-stats")
    public Result<List<Map<String, Object>>> getCategoryStats() {
        log.info("获取教程分类统计");
        
        List<Map<String, Object>> stats = tutorialService.getCategoryStats();
        
        return Result.success(stats);
    }
    
    /**
     * 点赞/取消点赞教程
     */
    @PostMapping("/{id}/like")
    public Result<Map<String, Object>> likeTutorial(@PathVariable Long id) {
        Long userId = SecurityUtils.getCurrentUserId();
        log.info("用户{}点赞教程: {}", userId, id);
        
        Map<String, Object> result = tutorialService.likeTutorial(id, userId);
        
        return Result.success(result);
    }
    
    /**
     * 收藏/取消收藏教程
     */
    @PostMapping("/{id}/favorite")
    public Result<Map<String, Object>> favoriteTutorial(@PathVariable Long id) {
        Long userId = SecurityUtils.getCurrentUserId();
        log.info("用户{}收藏教程: {}", userId, id);
        
        Map<String, Object> result = tutorialService.favoriteTutorial(id, userId);
        
        return Result.success(result);
    }
    
    /**
     * 获取用户对教程的互动状态
     */
    @GetMapping("/{id}/interaction")
    public Result<Map<String, Object>> getTutorialInteraction(@PathVariable Long id) {
        Long userId = SecurityUtils.getCurrentUserId();
        log.info("获取用户{}对教程{}的互动状态", userId, id);
        
        Map<String, Object> interaction = tutorialService.getTutorialInteraction(id, userId);
        
        return Result.success(interaction);
    }
    
    /**
     * 增加浏览量
     */
    @PostMapping("/{id}/view")
    public Result<Void> increaseViewCount(@PathVariable Long id) {
        log.info("增加教程浏览量: {}", id);
        
        tutorialService.increaseViewCount(id);
        
        return Result.success();
    }
    
    /**
     * 调试接口 - 测试用户ID获取
     */
    @GetMapping("/debug/user-id")
    public Result<Map<String, Object>> debugGetUserId() {
        try {
            Long userId = SecurityUtils.getCurrentUserId();
            Map<String, Object> result = new HashMap<>();
            result.put("userId", userId);
            result.put("message", "用户ID获取成功");
            return Result.success(result);
        } catch (Exception e) {
            log.error("调试获取用户ID失败", e);
            Map<String, Object> result = new HashMap<>();
            result.put("error", e.getMessage());
            return Result.error("获取用户ID失败: " + e.getMessage());
        }
    }
}